package servlets.category;

import hibernate.method.CategoryMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class CategoryAdd
 */
@WebServlet("/CategoryAdd")
public class CategoryAdd extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CategoryAdd() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String categoryName = (String) request.getParameter("categoryName");
		
		
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
				
		CategoryMethods catm = new CategoryMethods();
		catm.addCategory(sessionFactory, session, categoryName);
				
				try {
					session.getTransaction().commit();
					out.println("<script type=\"text/javascript\">alert(\"Kategoria dodana\"); window.location.href = \"management/index.jsp?page=games&group=categoryManagement\";</script>");
				} catch (Exception e) {
					out.println("<script type=\"text/javascript\">alert(\"Kategoria nie dodana\"); window.location.href = \"management/index.jsp?page=games&group=categoryManagement\";</script>");
				}
					
					
	}

}
